﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Kang.ExtendMethod
{
    public static class ByteExtendMethod
    {
        /// <summary>
        /// 保存字节数据至文件
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="path"></param>
        /// <param name="overwrite"></param>
        /// <returns></returns>
        public static bool WriteToFile(this byte[] datas, string path, bool overwrite = true)
        {
            if (datas == null)
            {
                return false;
            }
            if (File.Exists(path) && overwrite != true)
            {
                return false;
            }
            FileMode mode = overwrite ? FileMode.Create : FileMode.CreateNew;
            try
            {
                using (MemoryStream ms = new MemoryStream(datas))
                {
                    using (FileStream fs = new FileStream(path, mode, FileAccess.ReadWrite, FileShare.Read))
                    {
                        int readCount = 0;
                        int lenCount = 1024;
                        byte[] data = new byte[lenCount];
                        while ((readCount = ms.Read(data, 0, lenCount)) > 0)
                        {
                            fs.Write(data, 0, readCount);
                            fs.Flush();
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 保存字节数据至文件
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="path"></param>
        /// <param name="overwrite"></param>
        /// <returns></returns>
        public static string GetString(this byte[] datas, Encoding encoding = null)
        {
            if (datas == null)
            {
                return default;
            }
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            try
            {
                return encoding.GetString(datas);
            }
            catch
            {
                return default;
            }
        }
    }
}
